/* serial.c */

#include <avr/io.h>
#include "delay.h"

// Baudrate of 9600 bits per second means 9600 state changes per second
// that each take 104 nanoseconds.

void serial_init(volatile uint8_t* port, unsigned char pin)
{
   *port  = (1 << pin);
}

void serial_tx(volatile uint8_t* port, unsigned int pin, unsigned char c)
{
   *port &= ~(1 << pin);
   delay_us(104);
   
   for (unsigned char i = 0; i < 8; i++) {
      if (c & 0b00000001) {
         *port |= (1 << pin);
      } else {
         *port &= ~(1 << pin);         
      }
      delay_us(104);
      c >>= 1;
   }

   *port |= (1 << pin);
   delay_us(104);
}

void serial_tx_string(volatile uint8_t* port, unsigned int pin, char* s)
{
   while (*s) {
      serial_tx(port, pin, *s++);
   }
}
